package cn.northsea.controller;

import cn.northsea.pojo.Menu;
import cn.northsea.pojo.User;
import cn.northsea.pojo.UserVo;
import cn.northsea.service.MenuService;
import cn.northsea.service.RoleService;
import cn.northsea.service.UserService;


import cn.northsea.utils.AliyunSmsUtils;
import cn.northsea.utils.RandomUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @RequestMapping("/login")
    public String login(User user, Model model, HttpSession session) {
        User user2 = userService.login(user);
        if (user2 == null) {
            model.addAttribute("msg", "用户名密码错误");
            return "login";
        } else {
            List<Menu> userMenuOne = menuService.findMenuOneByUid(user2.getUserId());
            List<Menu> userMenu = menuService.findMenuByUid(user2.getUserId());
            session.setAttribute("user", user2);
            model.addAttribute("userMenu", userMenu);
            model.addAttribute("userMenuOne", userMenuOne);
            return "index";
        }
    }

    @RequestMapping("/code")
    @ResponseBody
    public String code(@RequestParam("userPhone") String phone, Model model) {
        String code = RandomUtil.getSixBitRandom();
        Jedis jedis = jedisPool.getResource();
        String key = "phone:code:" + phone;
        if (!jedis.exists(key)) {
            log.info("手机号已发送API短信接口，验证码是：" + code);
            jedis.set(key, code);
            //有效期60秒
            jedis.expire(key, 60);
            Map<String, String> map = new HashMap<>();
            map.put("phoneNumbers", phone);
            map.put("signName", "进销存企业管理系统");
            map.put("templateCode", "SMS_475925036");
            map.put("templateParam", "{\"code\":\"" + code + "\"}");
            Boolean sms_result = AliyunSmsUtils.sendSms(map);
            System.out.println("工具类短信发送是否成功：" + sms_result);
            model.addAttribute("code", code);
            return "ok";
        }
        return "false";
    }

    @RequestMapping("/register")
    public String register(User user, @RequestParam("code") String code, Model model) {
        Jedis jedis = jedisPool.getResource();
        String key = "phone:code:" + user.getUserPhone();

        if (code != null && code.equals(jedis.get(key))) {
            userService.register(user);
            return "login";
        } else {
            return "register";
        }

    }


    @RequestMapping("/supplyIndex")
    public String supplyIndex(User user, Model model, HttpSession session) {
        User user2 = userService.login(user);
        if (user2 == null) {
            model.addAttribute("msg", "用户名密码错误");
            return "login";
        } else {
            session.setAttribute("user", user2);
            return "index2";
        }
    }

    @RequestMapping("/findAll")
    public String findAll(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                          @RequestParam(required = false, defaultValue = "3") Integer pageSize,
                          Model model,
                          @RequestParam(required = false, defaultValue = "") String likename,
                          @RequestParam(required = false, defaultValue = "") String start,
                          @RequestParam(required = false, defaultValue = "") String end) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserVo> userVoList = null;
        PageInfo<UserVo> userPageInfo = null;
        userVoList = userService.findAll(likename, start, end);
        userPageInfo = new PageInfo<>(userVoList);
        model.addAttribute("likename", likename);
        model.addAttribute("start", start);
        model.addAttribute("end", end);
        model.addAttribute("Page", userPageInfo);
        return "userList";

    }

    @RequestMapping("/find")
    public String find(Integer userId, Model model) {
        User user = userService.findUserById(userId);
        model.addAttribute("user", user);
        return "userIndex";
    }

    @Autowired
    private RoleService roleService;

    @RequestMapping("/updateUser")
    public String updateUser(User user, HttpSession httpSession) {
        System.out.println(user.toString());
        userService.updateUser(user);
        User user1 = userService.findUserById(user.getUserId());
        httpSession.setAttribute("user", user1);
        return "userIndex";
    }

    @RequestMapping("/checkUsername")
    @ResponseBody
    public String check(String userUsername) {
        User user1 = userService.check(userUsername);
        if (user1 == null) {
            return "OK";
        } else {
            return "ERROR";
        }
    }


    @RequestMapping("/delUser")
    public String delUser(Integer[] ids) {
        userService.delUser(ids);
        return "redirect:/user/findAll.do";
    }

    @RequestMapping("/huiFu")
    public String huiFu(Integer pageNum, Integer userId, Model model) {
        userService.huiFu(userId);
        model.addAttribute("pageNum", pageNum);
        return "redirect:/user/findAll.do";
    }


}
